﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.PressReleases
{
    public static class Create
    {
        public static Adams.Admin.DataTransfer.PressReleases.Create.PageLoad PageLoad(int id)
        {
            var data = new Adams.Admin.DataTransfer.PressReleases.Create.PageLoad();
            data.PressRelease = new Shared.Entities.PressReleases.PressRelease();

            if (id > 0)
            {
                using (SqlDataReader dr = DB.RunDataReader(@"
SELECT * FROM PressReleases.PressReleases WHERE PressReleaseID = @PressReleaseID
", CommandType.Text,
                DB.CreateParameter("@PressReleaseID", id, SqlDbType.Int)))
                {
                    dr.Read();
                    data.PressRelease.ID = dr["PressReleaseID"].DbInt();
                    data.PressRelease.Title = dr["Title"].DbString();
                    data.PressRelease.ShortDescription = dr["ShortDescription"].DbString();
                    data.PressRelease.LongDescription = dr["LongDescription"].DbString();
                    data.PressRelease.ReleaseDate = dr["ReleaseDate"].DbDate();
                }
            }

            return data;
        }

        public static void Save(DataTransfer.PressReleases.Create.FormInput input)
        {
            DB.Run(@"
IF(@PressReleaseID > 0)
BEGIN
    UPDATE PressReleases.PressReleases SET
        Title = @Title
        ,ShortDescription = @ShortDescription
        ,LongDescription = @LongDescription
        ,ReleaseDate = @ReleaseDate
    WHERE PressReleaseID = @PressReleaseID
END
ELSE
BEGIN
    INSERT INTO PressReleases.PressReleases (
        Title
        ,ShortDescription
        ,LongDescription
        ,ReleaseDate)
    VALUES (
        @Title
        ,@ShortDescription
        ,@LongDescription
        ,@ReleaseDate)
END
    ", CommandType.Text,
                    DB.CreateParameter("@PressReleaseID", input.ID.ToInt(), SqlDbType.Int),
                    DB.CreateParameter("@Title", input.Title.ToNString(), SqlDbType.VarChar, 50),
                    DB.CreateParameter("@ShortDescription", input.ShortDescription.ToNString(), SqlDbType.VarChar, 255),
                    DB.CreateParameter("@LongDescription", input.LongDescription.ToNString(), SqlDbType.Text),
                    DB.CreateParameter("@ReleaseDate", input.ReleaseDate.ToNString(), SqlDbType.SmallDateTime));
        }
    }
}
